package main

import (
	"io"
	"strconv"
)

// proto
//  ----------------
// | size | content |

const (
	size = 2 // 2 byte head size
)

type StreamReader struct {
	r io.Reader
	h []byte // head buffer
}

func NewStreamReader(r io.Reader) *StreamReader {
	return &StreamReader{r: r, h: make([]byte, size)}
}

func (this *StreamReader) Read() ([]byte, error) {
	_, err := io.ReadAtLeast(this.r, this.h, size)
	if err != nil {
		return nil, err
	}

	n, err := strconv.ParseInt(string(this.h), 10, 16)
	if err != nil {
		return nil, err
	}

	b := make([]byte, n)
	_, err = io.ReadAtLeast(this.r, b, int(n))
	if err != nil {
		return nil, err
	}

	return b, nil
}
